<!-- pages/member/activate-card/index.vue -->
<template>
  <view class="activate-card-page">
    <!-- 顶部导航 -->
    <!-- <view class="nav-header">
      <view class="nav-back" @click="handleBack">
        <text class="icon-back">‹</text>
        <text class="nav-title">会员卡开通</text>
      </view>
    </view> -->

    <!-- 页面内容 -->
    <scroll-view class="page-content" scroll-y>
      <!-- 卡片展示 -->
   <!--   <card-design
        :card-info="cardInfo"
        :loading="loading"
      /> -->

      <!-- 开卡表单 -->
      <member-card-form
        ref="formRef"
        :custom-fields="customFields"
        :initial-data="initialFormData"
      />

      <!-- 提交按钮 -->
      <view class="submit-section">
        <button
          class="submit-btn"
          :class="{ disabled: !canSubmit }"
          :disabled="!canSubmit"
          @click="handleSubmit"
          :loading="submitting"
        >
          {{ submitButtonText }}
        </button>
        
        <view class="submit-tips">
          点击开通即代表同意相关协议
        </view>
      </view>
    </scroll-view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-mask">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载中...</text>
      </view>
    </view>
  </view>
</template>

<script>
import WechatSDK from '@/utils/wx-sdk';
import { getUserInfo } from '@/utils/user-info';
import api from '@/api/wxcard.js';
import CardDesign from '@/components/card-design.vue';
import MemberCardForm from '@/components/member-card-form.vue';

export default {
  components: {
    CardDesign,
    MemberCardForm
  },
  
  data() {
    return {
      isH5: true,
      loading: false,
      submitting: false,
      cardId: '',
      cardInfo: {},
      customFields: [],
      initialFormData: {},
      wechatUserInfo: null,
	  form:{
		  card_id:0
	  }
    };
  },
  
  computed: {
    canSubmit() {
      return !this.submitting && !this.loading;
    },
    
    submitButtonText() {
      return this.submitting ? '开通中...' : '立即开通会员';
    }
  },
  
  onLoad(options) {
	  console.log(options);
    this.cardId = options.cardId || '';
	this.form.card_id = options.cardId || '';
    
    this.initPage();
  },
  
  onShow() {
    // 设置微信分享
    if (this.isH5) {
      this.setWechatShare();
    }
  },
  
  methods: {
    async initPage() {
      this.loading = true;
      
      try {
        // 初始化微信 SDK
        if (this.isH5) {
          await WechatSDK.init();
          //await this.getWechatUserInfo();
		  
		  const response = await getUserInfo()
		  console.log(response,'88888888888')
        }
        
        // 加载卡券信息
        await this.loadCardInfo();
        
        // 预填充表单数据
        this.prefillFormData();
        
      } catch (error) {
        console.error('页面初始化失败:', error);
        uni.showToast({
          title: error.message || '页面加载失败',
          icon: 'none',
          duration: 3000
        });
        
        // 错误处理：3秒后返回
        setTimeout(() => {
          this.handleBack();
        }, 3000);
      } finally {
        this.loading = false;
      }
    },
    async loadCardInfo() {
      if (!this.cardId) {
        throw new Error('卡券ID不能为空');
      }
     let clone = this.form;
	  api.getCardInfo(clone).then(res => {
	  	console.log(res,444444);
		if(res.code==1){
			 this.cardInfo = res.data;
			 this.customFields = res.data.customFields || [];
		}else{
			uni.showToast({
				title: "卡券信息加载失败",
				icon: 'none',
				duration: 1000
			});
		}
	  	
	  })
      // 更新页面标题
      uni.setNavigationBarTitle({
        title: this.cardInfo.title || '会员卡开通'
      });
    },
    
    prefillFormData() {
      // 如果有微信用户信息，预填充部分字段
      if (this.wechatUserInfo) {
        this.initialFormData = {
          ...this.initialFormData,
          name: this.wechatUserInfo.nickname || ''
        };
      }
      
      // 预填充其他逻辑...
    },
    
    setWechatShare() {
      const shareData = {
        title: `立即领取${this.cardInfo.title}，尊享会员特权`,
        desc: this.cardInfo.description || '快来领取专属会员卡，享受更多优惠权益',
        link: window.location.href,
        imgUrl: this.cardInfo.logo || '/static/images/share-logo.png'
      };
      
      WechatSDK.setShareConfig(shareData);
    },
    
    async handleSubmit() {
      if (!this.canSubmit) return;
      
      // 表单验证
      if (!this.$refs.formRef.validateAll()) {
        return;
      }
      
      this.submitting = true;
      
      try {
        const formData = this.$refs.formRef.getFormData();
        
        // 1. 提交表单数据到后端
        const submitResponse = await memberCardApi.submitFormData({
          cardId: this.cardId,
          ...formData,
          wechatUserInfo: this.wechatUserInfo
        });
        
        if (!submitResponse.success) {
          throw new Error(submitResponse.message || '表单提交失败');
        }
        
        // 2. H5 环境：调用微信添加卡券
        if (this.isH5) {
          await this.addWechatCard(submitResponse.data.activateData);
        }
        
        // 3. 跳转到成功页面
        this.navigateToSuccess(submitResponse.data);
        
      } catch (error) {
        console.error('开卡失败:', error);
        uni.showToast({
          title: error.message || '开卡失败，请重试',
          icon: 'none',
          duration: 3000
        });
      } finally {
        this.submitting = false;
      }
    },
    
    async addWechatCard(activateData) {
      try {
        // 获取微信卡券参数
        const cardParams = await memberCardApi.getWechatCardParams({
          cardId: this.cardId,
          activateData: activateData
        });
        
        if (cardParams.success) {
          // 调用微信添加卡券
          const result = await WechatSDK.addCard(cardParams.data.cardList);
          
          if (result.cardList && result.cardList.length > 0) {
            const cardResult = result.cardList[0];
            if (!cardResult.isSuccess) {
              console.warn('微信卡券添加结果:', cardResult);
            }
          }
        }
      } catch (error) {
        console.error('添加微信卡券失败:', error);
        // 这里不抛出错误，因为业务数据已经提交成功
        // 只是微信卡券添加失败，可以提示用户手动添加
      }
    },
    
    navigateToSuccess(data) {
      uni.redirectTo({
        url: `/pages/member/activate-card/success?cardId=${this.cardId}&memberId=${data.memberId}`,
        success: () => {
          // 可以在这里传递数据到成功页面
        }
      });
    },
    
    handleBack() {
      //uni.navigateBack();
    }
  }
};
</script>

<style scoped>
.activate-card-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.nav-header {
  height: 88rpx;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10rpx);
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.nav-back {
  display: flex;
  align-items: center;
}

.icon-back {
  font-size: 48rpx;
  color: #333;
  margin-right: 20rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.page-content {
  height: 100vh;
  padding-top: 88rpx;
  box-sizing: border-box;
}

.submit-section {
  padding: 40rpx 30rpx 60rpx;
}

.submit-btn {
  background: linear-gradient(135deg, #FF6B6B, #FF8E53);
  color: white;
  border: none;
  border-radius: 50rpx;
  height: 100rpx;
  line-height: 100rpx;
  font-size: 36rpx;
  font-weight: bold;
  box-shadow: 0 8rpx 30rpx rgba(255, 107, 107, 0.3);
}

.submit-btn.disabled {
  background: #cccccc;
  box-shadow: none;
}

.submit-tips {
  text-align: center;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.7);
  margin-top: 20rpx;
}

.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-content {
  background: white;
  border-radius: 20rpx;
  padding: 60rpx 80rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #07C160;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>